<template>
  <div class="datasource-manager">
    <div class="header">
      <div class="header-left">
        <h3>数据源管理</h3>
        <span class="count">共 {{ datasources.length }} 个数据源</span>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          添加数据源
        </el-button>
        <el-button @click="handleRefresh" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <div class="search-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索数据源名称、类型或主机地址"
        clearable
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-select v-model="typeFilter" placeholder="筛选类型" clearable style="width: 150px; margin-left: 12px;">
        <el-option label="MySQL" value="mysql" />
        <el-option label="PostgreSQL" value="postgresql" />
        <el-option label="SQL Server" value="sqlserver" />
        <el-option label="Oracle" value="oracle" />
      </el-select>
      <el-select v-model="statusFilter" placeholder="筛选状态" clearable style="width: 150px; margin-left: 12px;">
        <el-option label="已连接" value="connected" />
        <el-option label="未连接" value="disconnected" />
        <el-option label="连接中" value="connecting" />
      </el-select>
    </div>

    <div class="content" v-loading="loading">
      <div v-if="filteredDatasources.length === 0" class="empty-state">
        <el-empty description="暂无数据源">
          <el-button type="primary" @click="handleAdd">添加第一个数据源</el-button>
        </el-empty>
      </div>
      
      <div v-else class="datasource-grid">
        <div
          v-for="datasource in filteredDatasources"
          :key="datasource.id"
          class="datasource-card"
          @click="handleSelect(datasource)"
        >
          <div class="card-header">
            <div class="title-section">
              <h4>{{ datasource.name }}</h4>
              <el-tag
                :type="getStatusType(datasource.status)"
                size="small"
                class="status-tag"
              >
                {{ getStatusText(datasource.status) }}
              </el-tag>
            </div>
            <div class="actions">
              <el-dropdown @command="handleCommand" trigger="click">
                <el-button text>
                  <el-icon><MoreFilled /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="`edit-${datasource.id}`">
                      <el-icon><Edit /></el-icon>
                      编辑
                    </el-dropdown-item>
                    <el-dropdown-item :command="`test-${datasource.id}`">
                      <el-icon><Connection /></el-icon>
                      测试连接
                    </el-dropdown-item>
                    <el-dropdown-item :command="`delete-${datasource.id}`" divided>
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
          
          <div class="card-content">
            <div class="info-row">
              <el-icon class="info-icon"><DataBoard /></el-icon>
              <span class="info-label">类型:</span>
              <span class="info-value">{{ getDatabaseTypeText(datasource.type) }}</span>
            </div>
            <div class="info-row">
              <el-icon class="info-icon"><Monitor /></el-icon>
              <span class="info-label">主机:</span>
              <span class="info-value">{{ datasource.host }}:{{ datasource.port }}</span>
            </div>
            <div class="info-row" v-if="datasource.description">
              <el-icon class="info-icon"><Document /></el-icon>
              <span class="info-label">描述:</span>
              <span class="info-value">{{ datasource.description }}</span>
            </div>
          </div>
          
          <div class="card-footer">
            <el-button type="primary" size="small" @click.stop="handleSelect(datasource)">
              <el-icon><Right /></el-icon>
              查看数据库
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑数据源对话框 -->
    <el-dialog
      v-model="showDialog"
      :title="isEdit ? '编辑数据源' : '添加数据源'"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="数据源名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入数据源名称" />
        </el-form-item>
        
        <el-form-item label="数据库类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择数据库类型" style="width: 100%;">
            <el-option label="MySQL" value="mysql" />
            <el-option label="PostgreSQL" value="postgresql" />
            <el-option label="SQL Server" value="sqlserver" />
            <el-option label="Oracle" value="oracle" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="主机地址" prop="host">
          <el-input v-model="form.host" placeholder="请输入主机地址" />
        </el-form-item>
        
        <el-form-item label="端口" prop="port">
          <el-input-number
            v-model="form.port"
            :min="1"
            :max="65535"
            placeholder="请输入端口号"
            style="width: 100%;"
          />
        </el-form-item>
        
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="描述">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入数据源描述（可选）"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ isEdit ? '更新' : '添加' }}
        </el-button>
        <el-button @click="handleTestConnection" :loading="testing">
          测试连接
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Refresh,
  Search,
  MoreFilled,
  Edit,
  Delete,
  Connection,
  DataBoard,
  Monitor,
  Document,
  Right
} from '@element-plus/icons-vue'

const props = defineProps({
  datasources: {
    type: Array,
    default: () => []
  },
  loading: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['select', 'add', 'edit', 'delete', 'refresh'])

// 搜索和筛选
const searchKeyword = ref('')
const typeFilter = ref('')
const statusFilter = ref('')

// 对话框状态
const showDialog = ref(false)
const isEdit = ref(false)
const submitting = ref(false)
const testing = ref(false)

// 表单相关
const formRef = ref()
const form = ref({
  id: '',
  name: '',
  type: '',
  host: '',
  port: 3306,
  username: '',
  password: '',
  description: ''
})

const rules = {
  name: [
    { required: true, message: '请输入数据源名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择数据库类型', trigger: 'change' }
  ],
  host: [
    { required: true, message: '请输入主机地址', trigger: 'blur' }
  ],
  port: [
    { required: true, message: '请输入端口号', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 计算属性
const filteredDatasources = computed(() => {
  let result = props.datasources

  // 关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(ds =>
      ds.name.toLowerCase().includes(keyword) ||
      ds.type.toLowerCase().includes(keyword) ||
      ds.host.toLowerCase().includes(keyword)
    )
  }

  // 类型筛选
  if (typeFilter.value) {
    result = result.filter(ds => ds.type === typeFilter.value)
  }

  // 状态筛选
  if (statusFilter.value) {
    result = result.filter(ds => ds.status === statusFilter.value)
  }

  return result
})

// 方法
const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const handleRefresh = () => {
  emit('refresh')
}

const handleSelect = (datasource) => {
  emit('select', datasource)
}

const handleAdd = () => {
  isEdit.value = false
  resetForm()
  showDialog.value = true
}

const handleCommand = (command) => {
  const [action, id] = command.split('-')
  const datasource = props.datasources.find(ds => ds.id === id)
  
  if (!datasource) return
  
  switch (action) {
    case 'edit':
      handleEdit(datasource)
      break
    case 'test':
      handleTestConnection(datasource)
      break
    case 'delete':
      handleDelete(datasource)
      break
  }
}

const handleEdit = (datasource) => {
  isEdit.value = true
  form.value = { ...datasource }
  showDialog.value = true
}

const handleDelete = (datasource) => {
  emit('delete', datasource)
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    // 模拟提交
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (isEdit.value) {
      emit('edit', form.value)
    } else {
      emit('add', form.value)
    }
    
    showDialog.value = false
    ElMessage.success(isEdit.value ? '数据源更新成功' : '数据源添加成功')
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitting.value = false
  }
}

const handleTestConnection = async (datasource = null) => {
  const testData = datasource || form.value
  
  if (!testData.host || !testData.port || !testData.username) {
    ElMessage.warning('请填写完整的连接信息')
    return
  }
  
  testing.value = true
  try {
    // 模拟连接测试
    await new Promise(resolve => setTimeout(resolve, 2000))
    ElMessage.success('连接测试成功')
  } catch (error) {
    ElMessage.error('连接测试失败')
  } finally {
    testing.value = false
  }
}

const resetForm = () => {
  form.value = {
    id: '',
    name: '',
    type: '',
    host: '',
    port: 3306,
    username: '',
    password: '',
    description: ''
  }
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const getStatusType = (status) => {
  const statusMap = {
    connected: 'success',
    disconnected: 'danger',
    connecting: 'warning'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    connected: '已连接',
    disconnected: '未连接',
    connecting: '连接中'
  }
  return statusMap[status] || '未知'
}

const getDatabaseTypeText = (type) => {
  const typeMap = {
    mysql: 'MySQL',
    postgresql: 'PostgreSQL',
    sqlserver: 'SQL Server',
    oracle: 'Oracle'
  }
  return typeMap[type] || type
}

// 监听数据库类型变化，设置默认端口
watch(() => form.value.type, (newType) => {
  const defaultPorts = {
    mysql: 3306,
    postgresql: 5432,
    sqlserver: 1433,
    oracle: 1521
  }
  if (defaultPorts[newType] && !isEdit.value) {
    form.value.port = defaultPorts[newType]
  }
})
</script>

<style scoped>
.datasource-manager {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left h3 {
  margin: 0 0 4px 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.count {
  color: #909399;
  font-size: 14px;
}

.header-right {
  display: flex;
  gap: 12px;
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 12px;
}

.search-bar .el-input {
  flex: 1;
  min-width: 200px;
}

.content {
  flex: 1;
  overflow: auto;
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 300px;
}

.datasource-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.datasource-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  background: white;
  cursor: pointer;
  transition: all 0.3s ease;
}

.datasource-card:hover {
  border-color: #409eff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.title-section h4 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.status-tag {
  margin-left: 8px;
}

.card-content {
  margin-bottom: 16px;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
}

.info-icon {
  color: #909399;
  margin-right: 8px;
  width: 16px;
}

.info-label {
  color: #606266;
  margin-right: 8px;
  min-width: 40px;
}

.info-value {
  color: #303133;
  flex: 1;
  word-break: break-all;
}

.card-footer {
  display: flex;
  justify-content: flex-end;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .datasource-manager {
    padding: 16px;
  }
  
  .header {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
  
  .header-right {
    justify-content: center;
  }
  
  .search-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-bar .el-input {
    min-width: auto;
  }
  
  .datasource-grid {
    grid-template-columns: 1fr;
  }
  
  .card-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .title-section {
    margin-bottom: 12px;
  }
}
</style>